package com.usermanage.ServiceImpl;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.usermanage.Mapping.PermissionMapping;
import com.usermanage.SecurityConfig.SpringSecurityUtils;
import com.usermanage.SecurityConfig.UserDetail;
import com.usermanage.Service.PermissionService;
import com.usermanage.beanParam.PermissionBean;
import com.usermanage.util.JsonData;
import com.usermanage.util.LevelUtil;
import com.usermanage.util.StringUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by  on 2018/9/16
 */
@Service("permissionService")
public class PermissionServiceImpl implements PermissionService {

    @Resource
    private PermissionMapping permissionMapping;

    @Override
    public List<PermissionBean> findPermissionByGroupId(String groupId) {
//        List<PermissionBean> list =permissionMapping.findAll();
        //查出所有权限列表
        List<PermissionBean> list = StringUtil.convertListMapToListBean(permissionMapping.findPermissionListByGroupId(groupId),PermissionBean.class);
        //把权限列表转换成树结构
        List<PermissionBean> result = groupListToTree(list);
        return result;
    }

    @Override
    public List<PermissionBean> findPermissionNewByGroupId(String groupIds) {
//        String[] groupId = groupIds.split(",");
//        Set set = new HashSet<>();
//        List<Map> newList = new ArrayList<>();
//        for (int i = 0; i < groupId.length; i++) {
//          List<Map> list =  permissionMapping.findPermissionListByGroupId(groupId[i]);
//          StringUtil.mapCopy(list,newList);
//        }
//        for (int i = 0; i < newList.size(); i++) {
//            set.add(newList.get(i));
//        }
//        List<Map> perssionList = new ArrayList<>(set);
//        List<PermissionBean> list = StringUtil.convertListMapToListBean(perssionList,PermissionBean.class);
////        List<PermissionBean> list =permissionMapping.findAll();
//        //查出所有权限列表
////        List<PermissionBean> list = StringUtil.convertListMapToListBean(permissionMapping.findPermissionListByGroupId(groupId),PermissionBean.class);
//        //把权限列表转换成树结构
//        Collections.sort(list, new Comparator<PermissionBean>() {
//            @Override
//            public int compare(PermissionBean o1, PermissionBean o2) {
//                Integer name1 = Integer.valueOf(o1.getId()) ;//name1是从你list里面拿出来的一个
//                Integer name2 = Integer.valueOf(o2.getId()) ; //name1是从你list里面拿出来的第二个name
//
//                return name1.compareTo(name2);
//            }
//        });
            UserDetail userDetail = SpringSecurityUtils.getCurrentUser();
        List<PermissionBean> result = groupListToTree(userDetail.getList());
        return result;
    }

    @Override
    public List<PermissionBean> findPermissionByGroupIdNotTree(String groupId) {
//        List<PermissionBean> list =permissionMapping.findAll();
        List<PermissionBean> list = StringUtil.convertListMapToListBean(permissionMapping.findPermissionListByGroupId(groupId),PermissionBean.class);
        return list;
    }

    @Override
    public String findPermissionEndListByGroupId(String groupId) {
//        List<PermissionBean> list =permissionMapping.findAll();
        //查出所有权限列表
        List<PermissionBean> list = StringUtil.convertListMapToListBean(permissionMapping.findPermissionListByGroupId(groupId),PermissionBean.class);
        StringBuffer buffer = new StringBuffer();
        for (PermissionBean permissionBean:list) {
            //取3级列表
//            if(StringUtil.counter(permissionBean.getLevel(),".".charAt(0))==2){
                buffer.append(permissionBean.getId()).append(",");
//            }
        }
        return buffer.toString();
    }

    @Override
    public List<PermissionBean> findAllPermissionByGroupId(String groupId) {
//        PermissionBean bean = new PermissionBean();
//        bean.setGroup_id(groupId);
//        Example<PermissionBean> example = Example.of(bean);
        //根据组id查询
        List<PermissionBean> list = permissionMapping.findAll();
        List<PermissionBean> result = groupListToTree(list);
        return result;
    }

    @Override
    public List<PermissionBean> findPermissionByParentId(String parentId) {
        PermissionBean bean = new PermissionBean();
        bean.setParent_id(parentId);
        Example<PermissionBean> example = Example.of(bean);
        List<PermissionBean> list = permissionMapping.findAll(example);
        return list;
    }

    @Override
    public boolean isExist(String name,String url,String parentId) {
        PermissionBean bean = new PermissionBean();
        bean.setPermission_name(name);
        bean.setPermission_url(url);
        bean.setParent_id(parentId);
        Example<PermissionBean> example = Example.of(bean);
        boolean bool = permissionMapping.exists(example);
        return bool;
    }

    @Override
    public Optional findById(int id) {
        Optional<PermissionBean> optional = permissionMapping.findById(id);
        return optional;
    }

    @Override
    public PermissionBean save(PermissionBean bean) {
        return permissionMapping.save(bean);
    }


    public List<PermissionBean> groupListToTree(List<PermissionBean> groupList) {
        if (CollectionUtils.isEmpty(groupList)) {
            return Lists.newArrayList();
        }
        // level -> [group, group2, ...] Map<String, List<Object>>
        Multimap<String, PermissionBean> groupMap = ArrayListMultimap.create();
        List<PermissionBean> rootList = Lists.newArrayList();
        for (PermissionBean permissionBean : groupList) {
            permissionBean.setLabel(permissionBean.getPermission_name());
            permissionBean.setAddress(permissionBean.getPermission_url());
            groupMap.put(permissionBean.getLevel(), permissionBean);
            if (LevelUtil.ROOT.equals(permissionBean.getLevel())) {
                rootList.add(permissionBean);
            }
        }
        // 递归生成树
        transformDeptTree(rootList, LevelUtil.ROOT, groupMap);
        return rootList;
    }

    // level:0, 0, all 0->0.1,0.2
    // level:0.1
    // level:0.2
    public void transformDeptTree(List<PermissionBean> groupList, String level, Multimap<String, PermissionBean> permissionBeanMultimap) {
        for (int i = 0; i < groupList.size(); i++) {
            // 遍历该层的每个元素
            PermissionBean permissionBean = groupList.get(i);
            // 处理当前层级的数据
            String nextLevel = LevelUtil.calculateLevel(level, permissionBean.getId());
            // 处理下一层
            List<PermissionBean> list = (List<PermissionBean>) permissionBeanMultimap.get(nextLevel);
            if (CollectionUtils.isNotEmpty(list)) {
                // 设置下一层部门
                permissionBean.setChildren(list);
                // 进入到下一层处理
                transformDeptTree(list, nextLevel, permissionBeanMultimap);
            }
        }
    }
}
